import React, { Component } from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'

export default class Index extends Component {
    render() {
        const { routerList } = this.props
        // 过滤不需要重定向的数据
        const filterRoutes = routerList.filter(item => !item.to)
        // 过滤需要重定向的数据
        const redirectRoutes = routerList.filter(item => item.to)
        return (
            <div>
                <Switch>
                    {
                        filterRoutes.map((item, index) => {
                            return <Route path={item.path} render={() => {
                                let Com = item.com
                                // 判断是否需要拦截
                                if (item.auth && !sessionStorage.getItem('token')) {
                                    // <Redirect to = "/login"/>
                                    return <Redirect to = {{
                                        pathname: "/login",
                                        // state 保存参数
                                        state: {
                                            back: item.path
                                        }
                                    }}/>
                                } else {
                                    if (item.children) {
                                        return <Com child={item.children} />
                                    } else {
                                        return <Com />
                                    }
                                }
                            }} key={index} />
                        })
                    }
                    {/* 重定向功能 */}
                    {
                        redirectRoutes.map((item, index) => {
                            return <Redirect to={item.to} from={item.from} key={index} />
                        })
                    }
                </Switch>
            </div>
        )
    }
}
